<template>
  <el-upload
    ref="innerElUpload"
    :action="oss + action"
    :headers="headers"
    :data="param"
    :limit="limit"
    :show-file-list="false"
    :auto-upload="auto"
    :file-list="fileList"
    :on-change="handleChange"
    :accept="accept"
    :multiple="limit > 1"
    :name="limit > 1 ? 'files' : 'file'"
    :on-success="handleImageSuccess"
    :http-request="submit"
  >
    <slot />
  </el-upload>
</template>
<script>
import { getToken } from '@/utils/auth'
// import { upload } from '@/api/common.js'
import request from '@/utils/request'

export default {
  name: 'UploadComp',
  props: {
    limit: {
      type: Number,
      default: 1
    },
    accept: {
      type: String,
      default: 'image/jpg, image/png, image/jpeg'
    },
    action: {
      type: String,
      default: '/cloudcut-api/userinfo/upload'
    },
    param: {
      type: Object,
      default() {
        return {}
      }
    },
    auto: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      fileList: []
    }
  },
  computed: {
    oss() {
      return this.$oss
    },
    headers() {
      return {
        'X-Access-Token': getToken(),
        'X-Login-Type': 'user'
      }
    }
  },
  methods: {
    async handleChange(_file) {
      const file = _file.raw
      this.$emit('getUrl', URL.createObjectURL(file))
      this.$emit('getFile', file)
    },
    handleImageSuccess(res) {
      this.$message.success('上传成功')
      if (res.success) {
        const url = res.result.url || ''
        if (url) {
          this.$emit('ok', url)
        }
      }
    },
    async submit() {
      const form = new FormData()
      for (const key in this.param) {
        if (key !== 'files') {
          form.append(key, this.param[key])
        }
      }
      if (this.param.files) {
        this.param.files.forEach((file) => {
          form.append('files', file)
        })
      }

      const res = await request({
        url: this.oss + this.action,
        method: 'post',
        headers: {
          'Content-Type': 'multiple/form-data'
        },
        onUploadProgress: (progressEvent) => {
          if (progressEvent.lengthComputable) {
            const percent = Math.round(
              (progressEvent.loaded / progressEvent.total) * 100
            )
            this.$emit('getProgress', percent)
          }
        },
        data: form
      })
      if (res.success) {
        this.$message.success('上传成功')
        this.$emit('get', this.fileList)
        this.$emit('getResult', res.result)
      } else {
        this.$message.error(res.message)
        this.$emit('get')
      }
    },
    clearFiles() {
      this.$refs.innerElUpload.clearFiles()
      this.fileList = []
    }
  }
}
</script>
